﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoPartsSearch.Domain.Abstract;
using AutoPartsSearch.Domain.Abstract.Repositories;
using AutoPartsSearch.Domain.Common;
using AutoPartsSearch.Domain.Entities;
using AutoPartsSearch.Domain.Entities.Messages;

namespace AutoPartsSearch.Domain.Concrete
{
    public class SearchQueryProcessor : ISearchQueryProcessor
    {
        //TODO build message
        private ISearchQueryRepository _searchQueryRepository;
        private IMessageSender _messageSender;
        private IMessageBuilder _messageBuilder;
        private ISellerRepository _sellerRepository;

        public SearchQueryProcessor(ISearchQueryRepository searchQueryRepository, 
            IMessageSender messageSender,
            IMessageBuilder messageBuilder,
            ISellerRepository sellerRepository)
        {
            this._messageSender = messageSender;
            this._searchQueryRepository = searchQueryRepository;
            this._messageBuilder = messageBuilder;
            this._sellerRepository = sellerRepository;
        }

        public void Process(List<SearchQuery> searchQueries, Func<int, string> urlBuilder)
        {
            foreach (var searchQuery in searchQueries)
            {
                var id = this._searchQueryRepository.Add(searchQuery);
                var dbSearchQuery = this._searchQueryRepository.GetById(id);
                var message = this._messageBuilder.BuildSearchQuery(dbSearchQuery, urlBuilder);
                var sellers = this._sellerRepository.GetBySearchQuery(dbSearchQuery);
                var recipients = GetRecipients(sellers);
                message.To = recipients;
                this._messageSender.Send(message);
            }
            
        }

        private string GetRecipients(IEnumerable<Seller> sellers)
        {
            var sellersToSend = sellers.Where(x => x.ReceiveQueriesByEmail).ToArray();
            return MessageHelpers.GetRecipientsString(sellersToSend.Select(x => x.EMail));
        }
    }
}
